package com.controller.broker;

import com.rmi.RMIBrokerInterface;
import com.rmi.RMIBrokerInterfaceImpl;
import com.rmi.RMITLSClientSocketFactory;
import com.rmi.RMITLSServerSocketFactory;
import com.util.Constant;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.rmi.AlreadyBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * Created by Phillip on 2014/4/19.
 */
public class Broker {

    private Logger logger = Logger.getLogger(Broker.class);

    public static void main(String[] args) {


        PropertyConfigurator.configure(Constant.BROKER_PRO_STRING);


        Broker broker = new Broker();
        broker.logger.debug("Broker starts...");
        broker.startRMI();


    }

    public void startRMI() {


        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        logger.debug("RMI starts...");

        RMIBrokerInterfaceImpl rmiBrokerInterface = new RMIBrokerInterfaceImpl();

        try {
            RMIBrokerInterface stub = (RMIBrokerInterface) UnicastRemoteObject.exportObject(rmiBrokerInterface, 0,
                    new RMITLSClientSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"),
                    new RMITLSServerSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"));
            logger.debug("UnicastRemoteObject.exportObject done");

            Registry registry = LocateRegistry.getRegistry("localhost", 1099,
                    new RMITLSClientSocketFactory(Constant.SER_KEYSTORE_STRING, Constant.CLI_KEYSTORE_STRING, "huyifei"));
            logger.debug("LocateRegistry.getRegistry done\r\nstart binding...");

            registry.bind(Constant.RMIBROKER_STRING, stub);
            logger.debug("binding done");
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (AlreadyBoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
